Skip to content

Durga js events#539

Open
Saidurgasatturi wants to merge 2 commits intoaptyInc:mainfrom
Saidurgasatturi:durga-js-events
Open

Durga js events#539
Saidurgasatturi wants to merge 2 commits intoaptyInc:mainfrom
Saidurgasatturi:durga-js-events

Conversation

@Saidurgasatturi
Copy link
Copy Markdown

@Saidurgasatturi Saidurgasatturi commented Nov 5, 2025

Terms and Conditions

  • I Accept losing points if my PR does not follow the best practices mentioned below, which will impact my overall performance in training

HTML Best Practices

  • File Naming Convention:

  • Follow consistent and descriptive naming (e.g., dashboard.html, user-profile.html).

  • Use lowercase letters and hyphens instead of spaces.

  • Page Title:

  • Ensure the <title> tag is descriptive and aligns with the page content.

  • Include meaningful keywords for SEO if applicable.

  • Semantic Markup:

  • Use appropriate tags like <header>, <footer>, <section>, <article> for better readability and accessibility.

  • Accessibility Standards:

  • Ensure the use of alt attributes for images and proper labels for form elements.

  • Use ARIA roles where necessary.

  • Validation:

  • Ensure the code passes HTML validation tools without errors or warnings.

  • Structure and Indentation:

  • Maintain consistent indentation and proper nesting of tags.

  • Attributes:

  • Ensure all required attributes (e.g., src, href, type, etc.) are correctly used and not left empty.

CSS Best Practices

  • File Organization:

  • Use modular CSS files if applicable (e.g., base.css, layout.css, theme.css).

  • Avoid inline styles unless absolutely necessary.

  • Naming Conventions:

  • Use meaningful class names following BEM or other conventions (e.g., block__element--modifier).

  • Code Reusability:

  • Avoid duplicate code; use classes or mixins for shared styles.

  • Responsive Design:

  • Ensure proper usage of media queries for mobile, tablet, and desktop views.

  • Performance Optimization:

  • Minimize the use of unnecessary CSS selectors.

  • Avoid overly specific selectors and ensure selectors are not overly deep (e.g., avoid #id .class1 .class2 p).

  • Consistency:

  • Follow consistent spacing, indentation, and use of units (rem/em vs. px).

  • Maintain a single coding style (e.g., always use double or single quotes consistently).

Javascript Best Practices

  • File Organization:

  • Ensure scripts are modular and logically separated into files if needed.

  • Avoid mixing inline JavaScript with HTML.

  • Logic Optimization:

  • Check for redundancy and ensure the code is optimized for performance.

  • Avoid unnecessary API calls or DOM manipulations.

  • Solution Approach:

  • Confirm that the code solves the given problem efficiently.

  • Consider scalability for future enhancements.

  • Readability:

  • Use clear variable and function names.

  • Add comments for complex logic or algorithms.

  • Error Handling:

  • Ensure proper error handling for API calls or user input validation.

  • Code Quality:

  • Check for potential bugs (e.g., missing await, mishandling of null/undefined values).

  • Avoid unnecessary console.log statements in production code.

  • Security:

  • Avoid hardcoding sensitive data.

  • Sanitize user input to prevent XSS and other vulnerabilities.

  • Best Practices:

  • Use const and let instead of var.

  • Follow ES6+ standards where applicable.

@gemini-code-assist
Copy link
Copy Markdown

Summary of Changes

Hello @Saidurgasatturi, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces a series of new assignments and examples primarily focused on fundamental JavaScript event handling and DOM manipulation techniques. It covers essential concepts such as event flow, preventing default browser actions, and dynamic content updates, alongside some foundational CSS styling and animation demonstrations. The changes aim to provide clear, practical illustrations of these web development principles.

Highlights

  • JavaScript Event Handling Examples: Introduced multiple examples demonstrating core JavaScript event concepts, including event bubbling, event delegation, keyboard events (keydown/keyup), and event propagation (capture, target, bubble phases).
  • Event Control Mechanisms: Added examples illustrating how to control event behavior using event.preventDefault() to stop default actions (e.g., form submission) and event.stopPropagation() to prevent events from bubbling up the DOM tree.
  • Client-Side Form Validation: Implemented a comprehensive client-side form validation example for username, email, and password fields, providing real-time feedback to the user.
  • Dynamic Content with MutationObserver: Included an example showcasing the use of MutationObserver to create an inline editable div, allowing users to modify text directly within the page and observe DOM changes.
  • CSS Layout and Animations: Added basic CSS examples for responsive layouts using flexbox and media queries, as well as a simple CSS animation demonstrating a bouncing effect with responsive adjustments.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request adds several assignments demonstrating CSS features and JavaScript event handling. The implementations are a good start, but there are several areas for improvement regarding correctness, performance, and adherence to best practices. Key issues identified include inefficient event handlers causing flickering, fragile form validation logic that can fail with autofill, and usability bugs in interactive components. I've provided specific comments and suggestions to address these points and improve the overall quality of the code.

Comment on lines +1 to +12
document.getElementById("myForm").addEventListener("submit", function(event) {
const name = document.getElementById("name").value.trim();
const email = document.getElementById("email").value.trim();
const message = document.getElementById("message");
if (name === "" || email === "") {
event.preventDefault();
message.textContent = "Please fill out all fields before submitting!";
} else {
message.style.color = "green";
message.textContent = "Form submitted successfully!";
}
});
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The form submission is not prevented on success, which causes the page to reload immediately. As a result, the user will never see the 'Form submitted successfully!' message. A better pattern is to call event.preventDefault() at the beginning of the handler and then proceed with validation and displaying the appropriate message.

Suggested change
document.getElementById("myForm").addEventListener("submit", function(event) {
const name = document.getElementById("name").value.trim();
const email = document.getElementById("email").value.trim();
const message = document.getElementById("message");
if (name === "" || email === "") {
event.preventDefault();
message.textContent = "Please fill out all fields before submitting!";
} else {
message.style.color = "green";
message.textContent = "Form submitted successfully!";
}
});
document.getElementById("myForm").addEventListener("submit", function(event) {
event.preventDefault(); // Prevent submission to handle it with JS
const name = document.getElementById("name").value.trim();
const email = document.getElementById("email").value.trim();
const message = document.getElementById("message");
if (name === "" || email === "") {
message.textContent = "Please fill out all fields before submitting!";
} else {
message.style.color = "green";
message.textContent = "Form submitted successfully!";
}
});

Comment on lines +26 to +35
table.addEventListener("mouseout", (event) => {

if (event.target.tagName === "TD") {
for (let row of table.rows) {
for (let cell of row.cells) {
cell.classList.remove("highlight");
}
}
}
});
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The mouseout event handler is inefficient and causes a noticeable flickering effect. It iterates over every cell in the table to remove the highlight class each time the mouse leaves a single cell. A much better approach is to use the mouseleave event on the table element itself. This event fires only once when the mouse pointer moves out of the entire table, allowing you to clear all highlights efficiently.

table.addEventListener("mouseleave", () => {
  for (let row of table.rows) {
    for (let cell of row.cells) {
      cell.classList.remove("highlight");
    }
  }
});

});

email.addEventListener("input", () => {
const emailPattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/;
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The email validation regex is too restrictive. It will reject many valid email addresses, such as those with subdomains (e.g., test@mail.co.uk), longer top-level domains (e.g., .international), or different character sets. Consider using a more robust regex to ensure valid emails are not rejected.

Suggested change
const emailPattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/;
const emailPattern = /^\S+@\S+\.\S+$/;

Comment on lines +48 to +60
form.addEventListener("submit", (e) => {
e.preventDefault();

if (
username.classList.contains("valid") &&
email.classList.contains("valid") &&
password.classList.contains("valid")
) {
alert("Form submitted successfully!");
} else {
alert("Please fix errors before submitting.");
}
});
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The form submission logic relies on checking for a .valid class on each input. This approach is fragile. If a user uses browser autofill and clicks submit without interacting with the fields, the input events may not fire, the classes won't be added, and the form will be incorrectly considered invalid. A more robust solution is to explicitly run all validation checks for each field within the submit event handler itself before determining if the form is valid.

Comment on lines +21 to +24
editableDiv.addEventListener("click", () => {
const currentText = document.getElementById("textContent").textContent;
editableDiv.innerHTML = `<textarea>${currentText}</textarea>`;
});
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The click event listener is on editableDiv. When the user clicks to edit, the content is replaced by a <textarea>. However, a subsequent click inside the textarea will bubble up and re-trigger this same listener, causing the textarea to be re-rendered and losing any user input and focus. You should check the event.target to prevent this from happening when the textarea is already present.

editableDiv.addEventListener("click", (event) => {
  if (event.target.tagName === 'TEXTAREA') {
    return; // Already in edit mode, do nothing
  }
  const currentText = document.getElementById("textContent").textContent;
  editableDiv.innerHTML = `<textarea>${currentText}</textarea>`;
});

Comment on lines +5 to +15
level1.addEventListener("click", () => {
alert("Level 1 (Capture Phase)");
}, true);

level2.addEventListener("click", () => {
alert("Level 2 (Bubble Phase)");
});

level3.addEventListener("click", () => {
alert("Level 3 (Target Phase)");
});
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Using alert() for demonstration purposes is disruptive because it blocks the UI and halts script execution. For a better user and developer experience, it's recommended to use console.log(). This will output the event propagation sequence to the developer console without interrupting the application flow.

Suggested change
level1.addEventListener("click", () => {
alert("Level 1 (Capture Phase)");
}, true);
level2.addEventListener("click", () => {
alert("Level 2 (Bubble Phase)");
});
level3.addEventListener("click", () => {
alert("Level 3 (Target Phase)");
});
level1.addEventListener("click", () => {
console.log("Level 1 (Capture Phase)");
}, true);
level2.addEventListener("click", () => {
console.log("Level 2 (Bubble Phase)");
});
level3.addEventListener("click", () => {
console.log("Level 3 (Target Phase)");
});

@media (max-width: 768px) {
main {
flex-direction: column;
flex:1;
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The flex: 1 property here has no effect because its parent element, <body>, does not have display: flex. This line is redundant and can be removed. Also, there should be a space between the property and value for consistency (flex: 1).

Suggested change
flex:1;
flex: 1;

Comment on lines +5 to +12
parentDiv.addEventListener("click", function() {
alert("Parent div clicked!");
});

childDiv.addEventListener("click", function(event) {
alert("Child div clicked!");
event.stopPropagation();
});
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Using alert() is disruptive as it blocks the UI. For demonstrating event behavior, it's better to use console.log(), which logs messages to the developer console without interrupting the user or the application's execution flow.

Suggested change
parentDiv.addEventListener("click", function() {
alert("Parent div clicked!");
});
childDiv.addEventListener("click", function(event) {
alert("Child div clicked!");
event.stopPropagation();
});
parentDiv.addEventListener("click", function() {
console.log("Parent div clicked!");
});
childDiv.addEventListener("click", function(event) {
console.log("Child div clicked!");
event.stopPropagation();
});

if (mutation.addedNodes.length > 0) {
mutation.addedNodes.forEach((node) => {
if (node.tagName === "TEXTAREA") {
console.log("Textarea added to DOM ✅");
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

This console.log statement appears to be for debugging. As per the best practices mentioned in the pull request description, such logs should be removed from the final code to keep the console clean in production.

Comment on lines +9 to +12
node.addEventListener("blur", () => {
const newText = node.value.trim() || "No text entered";
editableDiv.innerHTML = `<span id="textContent">${newText}</span> <span class="icon">✏️</span>`;
});
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

For a better user experience, the textarea should be automatically focused when it appears. This allows the user to start typing immediately without needing an extra click.

          node.focus();
          node.addEventListener("blur", () => {
            const newText = node.value.trim() || "No text entered";
            editableDiv.innerHTML = `<span id="textContent">${newText}</span> <span class="icon">✏️</span>`;
          });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant